<?php
/**
 * Created by PhpStorm.
 * User: 王凯林
 * Date: 18/4/11
 * Time: 9:59
 */

namespace App\Service;


use App\Model\MoneyReport;
use App\Model\PeakReport;
use Illuminate\Support\Facades\Log;

class PeakReportService
{
    /*
     * 获取某用户收益额度
     */
    public function getUserPeak($uid)
    {
        return PeakReport::where('uid',$uid)->where('status',1)->sum('amount');
    }
    /*
     * 写入峰值表的记录
     */
    public function addUserPeak($uid,$paytime,$amount,$remark,$status)
    {
        $data=[
            'uid'=>$uid,
            'amount'=>$amount,
            'remark'=>$remark,
            'create_time'=>$paytime,
            'status'=>$status
        ];
       return PeakReport::create($data);
    }
    
    /*
     * 用户剩余的收益额度
     */
    public function residualLncome($uid)
    {
        $peak = $this->getUserPeak($uid);
        $income = MoneyReport::where('uid',$uid)->whereNotIn('types',[5])->sum('amount');
        $total = $peak-$income;
        //这里返回的是用户的剩余的收益额度,后续逻辑需要判段是否可以添加收益
        return $total;
    }
    /*
     * 用户的收益写入
     */
    public function addIncome($uid,$types,$amount,$provider_uid,$remark)
    {
        //判段用户的可写入额度;
        $total = $this->residualLncome($uid);
        if($total>0){
            //进行额度的判段,要是当前剩余的额度比要添加进来的钱少,就添加当前可用额度的值
            $income = $amount;//保存产生的收益额度
            if($total<$amount){
                $amount=$total;
                //此处应该有日志,说明用户的现有额度不能将现在产生的收益全部划入自己的账户当中!
                Log::info('用户ID为'.$uid.'的用户可用收益额度不能满足本次收益的全部写入,额度为:'.$total.'! 产生收益为:'.$income.'现写入以额度为准的收益:'.$total);
            }
            $data = [
                'uid'=>$uid,
                'types'=>$types,
                'amount'=>$amount,
                'remark'=>$remark,
                'create_time'=>time(),
                'provider_uid'=>$provider_uid,
                'status'=>1
            ];
           return MoneyReport::create($data);
        }else{
            Log::info('用户ID为'.$uid.'的用户可用额度不足,已为0或者小于0');
           return false;
        }

    }
    
    /*
     * 用户的剩余的收益额度和复投次数的接口数据
     */
    public function creditsAndTimes($uid)
    {
        //复投的次数统计减去开卡初始额度1次
       $count = PeakReport::where(['uid'=>$uid])->count();
       $times = $count-1;
        //额度
        $total = $this->residualLncome($uid);
        $double = [
            'times'=>$times,
            'total'=>$total,
        ];
        return $double;
    }

}